package com.ease.model.typehandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import oracle.spatial.geometry.JGeometry;
import oracle.sql.STRUCT;

import com.ease.common.util.Assertion;
import com.ease.model.type.GeoPoint;
import com.ease.model.util.OracleSpatialGeometryUtil;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;

/**
 * 
 * @author nathanleewei
 * 
 */
public class GeoPointTypeHandler extends GeometryTypeHandler {

	public GeoPointTypeHandler() {
		super();
	}

	private Object getResult(Object object) throws SQLException {
		if (null != object) {
			STRUCT struct = OracleSpatialGeometryUtil.oracleStruct(object);
			JGeometry geometry = JGeometry.load(struct);
			if (null != geometry) {
				return OracleSpatialGeometryUtil.toGeoPoint(geometry);
			}
		}
		return null;
	}

	//
	// public Object getResult(CallableStatement cs, int columnIndex) throws
	// SQLException {
	// return getResult(cs.getObject(columnIndex));
	// }
	//
	// public Object getResult(ResultSet rs, int columnIndex) throws
	// SQLException {
	// return getResult(rs.getObject(columnIndex));
	// }
	//
	// public Object getResult(ResultSet rs, String columnName) throws
	// SQLException {
	// return getResult(rs.getObject(columnName));
	// }
	//
	// public void setParameter(PreparedStatement ps, int i, Object parameter,
	// String jdbcType) throws SQLException {
	// Connection conn = this.getOracleConnection(ps);
	// Assertion.notNull(conn, "OracleConnection not found");
	//
	// JGeometry geometry = OracleSpatialGeometryUtil.fromGeoPoint((GeoPoint)
	// parameter);
	// STRUCT struct = JGeometry.store(geometry, conn);
	// ps.setObject(i, struct);
	// }

	public Object valueOf(String s) {
		// TODO
		return null;
	}

	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
		PreparedStatement ps = setter.getPreparedStatement();
		Connection conn = this.getOracleConnection(ps);
		Assertion.notNull(conn, "OracleConnection not found");

		JGeometry geometry = OracleSpatialGeometryUtil.fromGeoPoint((GeoPoint) parameter);
		STRUCT struct = JGeometry.store(geometry, conn);
		ps.setObject(setter.getParameterIndex(), struct);
	}

	public Object getResult(ResultGetter getter) throws SQLException {

		return getResult(getter.getResultSet().getObject(getter.getColumnName()));
		//
		// return getResult(rs.getObject(columnName));
		// return null;
	}
}
